<template>
  <div class="articles-container">
    <el-card shadow="always" class="el-card_boxCard">
      <el-row>
        <el-col :span="24">
          <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small" label-width="80px">
            <el-form-item label="关键字">
              <el-input class="el-input_inner" v-model="formInline.keyword" placeholder="根据文章标题搜索"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select class="el-input_inner" v-model="formInline.state" placeholder="请选择">
                <el-option label="启用" :value="1"></el-option>
                <el-option label="禁用" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetForm">清除</el-button>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
            <el-form-item class="el-button_adds">
              <el-button class="el-button_add" @click="handleClick" icon="el-icon-edit" type="text">新增技巧</el-button>
            </el-form-item>
          </el-form>
          <el-alert :title="`数据共${total}条`" type="info" show-icon :closable="false"> </el-alert>
          <el-table :data="list" style="width: 100%; padding: 20px">
            <el-table-column label="序号" width="80" type="index"> </el-table-column>
            <el-table-column prop="title" label="文章标题" width="300">
              <template slot-scope="scope">
                {{ scope.row.title }}
                <i class="el-icon-film" style="color: #00f; cursor: pointer" v-if="scope.row.videoURL"></i>
              </template>
            </el-table-column>
            <el-table-column prop="visits" label="阅读数" width="80"> </el-table-column>
            <el-table-column prop="username" label="录入人"> </el-table-column>
            <el-table-column prop="createTime" label="录入时间"> </el-table-column>
            <el-table-column prop="stateName" label="状态"> </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="preview(scope.row)">预览</el-button>
                <el-button type="text" size="small" @click="switchover(scope.row)">{{
                  scope.row.state === 1 ? '禁用' : '启用'
                }}</el-button>
                <el-button @click="handleClick(scope.row)" type="text" size="small" :disabled="scope.row.state === 1">修改</el-button>
                <el-button type="text" size="small" :disabled="scope.row.state === 1" @click="removes(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination background @size-change="changeSize" @current-change="changePager" :current-page="formInline.page" layout="->, prev, pager, next, sizes, jumper" :page-size="formInline.pagesize" :total="total">
            </el-pagination>
            <el-dialog title="新增文章" :visible.sync="add" width="70%" :before-close="handleClose">
              <span>
                <el-form :model="ruleForm" :rules="rules" ref="addRef" label-width="100px" class="demo-ruleForm">
                  <el-form-item label="文章标题" prop="title">
                    <el-input v-model="ruleForm.title"></el-input>
                  </el-form-item>

                  <el-form-item label="文章内容" prop="articleBody">
                    <!-- <el-input type="textarea" v-model="ruleForm.desc"></el-input> -->
                    <quill-editor v-model="ruleForm.articleBody"></quill-editor>
                  </el-form-item>
                  <el-form-item label="视频地址">
                    <el-input v-model="ruleForm.videoURL" placeholder="请输入视频地址"> </el-input>
                  </el-form-item>
                </el-form>
              </span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="add = false">取 消</el-button>
                <el-button type="primary" @click="handleAdd">确 定</el-button>
              </span>
            </el-dialog>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog title="预览文章" :visible="dialogVisible" :before-close="previewClose">
      <div>
        <h2>{{ previewDetail.title }}</h2>
        <span>{{ previewDetail.createTime }}{{ previewDetail.username }}<i class="el-icon-view"></i>{{ previewDetail.visits }}</span>
        <p v-html="previewDetail.articleBody"></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, changeState, remove, add, update, detail } from '@/api/hmmm/articles.js'

export default {
  name: 'articles',
  data () {
    return {
      previewDetail: {},
      dialogVisible: false,
      total: 0,
      data: [],
      pageSize: [5, 10, 20, 50],
      currentPage: 1,
      add: false,
      formInline: {
        keyword: '',
        state: null,
        page: 1,
        pagesize: 10
      },
      // 文章列表的数据，默认为空数据
      list: [],
      ruleForm: {
        videoURL: '',
        title: '',
        articleBody: '',
        id: ''
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: ['blur', 'change'] }],
        articleBody: [{ required: true, message: '请填写文章内容', trigger: ['blur', 'change'] }]
      }
    }
  },
  methods: {
    // 预览文章列表
    async preview (row) {
      console.log(row)
      // 点击开启弹窗
      this.dialogVisible = true
      try {
        const ret = await detail({
          id: row.id
        })
        console.log(ret)
        if (ret.status === 200) {
          this.$message.success('预览文章成功')
          this.previewDetail = row
        } else {
          this.$message.error('预览文章失败')
        }
      } catch {
        this.$message.error('预览文章失败')
      }
      console.log('preview')
    },
    previewClose () {
      this.$confirm('确认关闭？')
        .then(_ => {
          console.log(this.previewDetail)
          this.dialogVisible = false
        })
        .catch(_ => { })
    },
    // 修改文章列表
    handleClick (row) {
      this.add = true
      if (row.id) {
        this.ruleForm = {
          id: row.id,
          videoURL: row.videoURL,
          title: row.title,
          articleBody: row.articleBody
        }
      }
    },
    // 新增列表
    async handleAdd () {
      this.$refs.addRef.validate(async valid => {
        if (this.ruleForm.id) {
          if (!valid) return this.$message.error('请修改为正确的内容')
          const res = await update(this.ruleForm)
          if (res.status !== 200) return this.$message.error('服务器错误')
          this.$message.success('修改成功')
          this.add = false
        } else {
          if (!valid) return this.$message.error('请填写正确的内容')
          const res = await add(this.ruleForm)
          if (res.status !== 200) return this.$message.error('服务器错误')
          this.$message.success('添加成功')
          this.add = false
        }
        this.initList(this.formInline)
      })
    },
    onSubmit () {
      this.initList(this.formInline)
    },
    resetForm () {
      this.formInline = {
        keyword: '',
        state: null,
        page: 1,
        pagesize: 10
      }
      this.initList(this.formInline)
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.formInline.pagesize = val
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.formInline.page = val
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    // 切换启用禁用
    async switchover (row) {
      const obj = {
        id: row.id,
        state: row.state
      }
      const res = await changeState(obj)
      console.log(res)
      if (res.status !== 200) return this.$message.error('切换状态失败')
      this.$message.success('切换状态成功')
      row.state = row.state === 1 ? 0 : 1
      row.stateName = row.state === 1 ? '启用' : '禁用'
    },
    // 删除列表
    async removes (index, id) {
      const res = await remove(id)
      if (res.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.list.splice(index, 1)
      // this.initList(this.formInline)
    },
    // 初始化文章列表数据
    async initList (formInline) {
      const res = await list(formInline)
      console.log(res)
      if (res.status !== 200) return this.$message.error('获取文章列表失败')
      // 把请求到的数据，转存到 data 中
      this.list = res.data.items
      this.list.map(item => {
        item.createTime = this.$moment(item.createTime).format('YYYY-MM-DD hh:mm:ss')
        item.stateName = item.state === 1 ? '启用' : '禁用'
        return item
      })
      this.total = res.data.counts
    },
    changePager (page) {
      this.formInline.page = page
      this.initList(this.formInline)
    },
    changeSize (size) {
      this.formInline.pagesize = size
      this.initList(this.formInline)
    }
  },
  created () {
    this.initList(this.formInline)
  }
}
</script>

<style scoped lang="scss">
// 设置富文本编辑器的默认最小高度
::v-deep .ql-editor {
  min-height: 300px;
}

// 解决元素对齐问题
::v-deep .ql-snow .ql-picker-label::before {
  position: relative;
  top: -8px;
}

// 解决元素对齐问题
::deep .ql-picker-label > svg {
  position: relative;
  top: -6px;
}
::v-deep img {
  width: 100%;
}
.articles-container {
  padding: 1px;

  .el-card_boxCard {
    padding: 2px;

    .el-button_add {
      padding: 10px 15px;
      background-color: #67c23a;
      color: #ffffff;
      float: right;
      margin-right: -1px;
    }
    .demo-form-inline {
      position: relative;
      .el-button_adds {
        position: absolute;
        right: 0;
        margin-right: 0;
      }
    }
  }
  .dialog-footer {
    margin-right: 10px;
  }
}
</style>
